package protocol;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import statter.Stats;

public class CommSckClientOut implements Runnable {
	private String address;
	private int port;
	private CommandRelay cmdRly;
	private Thread thread;
	private Socket sckt;
	private ObjectOutputStream os;
	private Stats statter;
	
	public CommSckClientOut(CommandRelay cmdRly, Stats statter) {
		this("127.0.0.1",11167, cmdRly, statter);
	}
	
	public CommSckClientOut(String address, int port, CommandRelay cmdRly, Stats statter) {
		this.statter = statter;
		statter.addSection("Outgoing tcp thread");
		this.address = address;
		this.port = port;		
		this.cmdRly = cmdRly;
		thread = new Thread(this);
		thread.start();
	}

	@Override
	public void run() {
		try {
			sckt = new Socket(address, port);
			os = new ObjectOutputStream(sckt.getOutputStream());
			while (sckt.isConnected()) {
				statter.statStart("Outgoing tcp thread");
				Cmd cmd = cmdRly.getOutCmd(); 
				if (cmd != null) {
					os.writeObject(cmd);
				}
				else {
					try {
						Thread.sleep(75);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				statter.statEnd("Outgoing tcp thread");
			}
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}	
	}
}
